import 'dart:typed_data';

import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';

class LocalFileUtils {
  /// 请求照片和视频的权限
  static Future<bool> requestPermission() async {
    // 请求照片和视频的权限
    PermissionStatus photosPermission = await Permission.photos.request();
    PermissionStatus videosPermission = await Permission.videos.request();

    print("FileUtils#requestPermission 权限请求");
    if (photosPermission.isGranted && videosPermission.isGranted) {
      print("FileUtils#requestPermission 权限请求 成功");
      return true;
    } else {
      print("FileUtils#requestPermission 权限请求 失败");
      return false;
    }
  }

  /// 实时检查权限状态
  static Future<bool> checkPermission() async {
    // 实时获取照片和视频权限状态
    PermissionStatus photosPermission = await Permission.photos.status;
    PermissionStatus videosPermission = await Permission.videos.status;

    print("FileUtils#checkPermission 实时检查权限");
    if (photosPermission.isGranted && videosPermission.isGranted) {
      print("FileUtils#checkPermission 权限已授予");
      return true;
    } else {
      print("FileUtils#checkPermission 权限未授予");
      return false;
    }
  }

  // static Future<List<AssetEntity>> getVideosInFolder(AssetPathEntity file) async {
  // static Future<List<File>> getVideosInFolder() async {
  //   return [];
  // }

  static Future<List<AssetPathEntity>> getTopLevelFolder() async {
    return await PhotoManager.getAssetPathList(type: RequestType.video);
  }

  /// 获取视频文件夹列表及其包含的视频数量
  static Future<List<AssetPathEntity>> getVideoFolders() async {
    // 实时检查权限
    if (!await checkPermission()) {
      return [];
    }

    try {
      List<AssetPathEntity> videoPaths = await PhotoManager.getAssetPathList(
        type: RequestType.video,
        filterOption: FilterOptionGroup(
          containsPathModified: true,
        ),
      );
      return videoPaths;
    } catch (e) {
      print('获取视频文件夹失败: $e');
      return [];
    }
  }

  /// 获取指定文件夹下的视频列表
  static Future<List<AssetEntity>> getVideosFromFolder(AssetPathEntity folder) async {
    List<AssetEntity> videos = await folder.getAssetListPaged(
      page: 0,
      size: await folder.assetCountAsync,
    );
    return videos;
  }

  /// 获取视频的第一帧作为封面图像
  static Future<Uint8List?>? getVideoThumbnail(AssetEntity video) async {
    return await video.thumbnailDataWithSize(ThumbnailSize(200, 200));
  }

  static Future<List<AssetEntity>> getAssetsByIds(List<String> ids) async {
    List<AssetEntity> result = [];

    for (String id in ids) {
      // 逐一根据 id 获取对应的 AssetEntity
      AssetEntity? asset = await AssetEntity.fromId(id);
      if (asset != null) {
        result.add(asset); // 如果找到对应资源，添加到结果列表
      }
    }

    return result;
  }

  static Future<AssetEntity?> getAssetsById(String id) async {
    List<String> ids = [id];
    List<AssetEntity> result = await getAssetsByIds(ids);
    return result?.first;
  }

  /// 根据视频名称进行搜索
  static Future<List<AssetEntity>> searchVideos(String query) async {
    // 检查权限
    if (!await checkPermission()) {
      return [];
    }

    try {
      // 获取所有视频文件夹
      List<AssetPathEntity> videoFolders = await getVideoFolders();
      List<AssetEntity> matchingVideos = [];

      // 遍历文件夹，获取视频并过滤
      for (AssetPathEntity folder in videoFolders) {
        List<AssetEntity> videos = await getVideosFromFolder(folder);
        for (AssetEntity video in videos) {
          String? title = await video.titleAsync;
          if (title != null && title.toLowerCase().contains(query.toLowerCase())) {
            matchingVideos.add(video);
          }
        }
      }
      return matchingVideos;
    } catch (e) {
      print('视频搜索失败: $e');
      return [];
    }
  }
}
